<?php
namespace app\merchant\controller;
use think\Config;
use think\Db;

class Goods extends Init{
    function _initialize(){
        parent::_initialize();
        $this->model = model('admin/goods');
        $this->SpecGoodsPrice = model('admin/spec_goods_price');
        $this->goods_label = model('admin/goods_label');
        $this->code = model('admin/code');
        $this->store = model('admin/store');
    }

    public function goodsList(){
        if($this->request->isPost()){
            $store_id = session('store_id');
            $page = input('post.page');
            $limit = input('post.limit');
            $map = "g.store_id = {$store_id}";
            $goods_id = input('post.goods_id');
            if($goods_id){
               $map .= " AND g.goods_id = {$goods_id}";
            }
            $count = db('goods')->alias('g')
                                ->where($map)
                                ->count();
            $list = db('goods')->alias('g')
                               ->field("g.goods_id,g.name,g.method,g.method_value,g.sort,g.shelves,g.thumbnail_img")
                               ->where($map)
                               ->order('g.sort desc,g.goods_id')
                               ->page($page,$limit)
                               ->select();
            foreach($list as $key=>$value){
              $list[$key]['price'] = db('spec_goods_price')->where("goods_id = {$value['goods_id']}")->min('price');
              if($value['method'] == 0){
                  $list[$key]['method'] = '件';
              }elseif($value['method'] == 1){
                  $list[$key]['method'] = '克重';
              }
              $list[$key]['thumbnail_img'] = 'http://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$value['thumbnail_img'];
            }
            return json(array('code'=>0,'msg'=>'获取成功','data'=>$list,'count'=>$count));
        }
        $store_id = session('store_id');
        $goods = db('goods')->field('goods_id,name')->where("store_id = {$store_id}")->select();
        $this->assign(['goods_id'=>$goods_id,'goods'=>$goods]);
        return $this->fetch();
    }

    public function chooseShelves(){
       if($this->request->isGET()){
          $store_id = session('store_id');
          $map['store_id'] = $store_id;
          $map['goods_id'] = input('get.id');
          if(input('get.val')){
             $data['shelves'] = 1;
          }else{
             $data['shelves'] = 0;
          }
          if($data['shelves'] == 1){
              $change_shelves = db('goods')->where($map)->update($data);
              if($change_shelves){
                 return json(['msg'=>'上架成功']);
              }else{
                 return json(['msg'=>'修改失败']);
              }
          }elseif($data['shelves'] == 0){
               $change_shelves = db('goods')->where($map)->update($data);
               if($change_shelves){
                  return json(['msg'=>'下架成功']);
               }else{
                  return json(['msg'=>'修改失败']);
              }
          }
       }
    }

    public function goodsSort(){
       if($this->request->isGET()){
          $store_id = session('store_id');
          $map['store_id'] = $store_id;
          $map['goods_id'] = input('get.id');
          if(input('get.val')){
             $data['sort'] = input('get.val');
          }else{
             $data['sort'] = 0;
          }
       }
    }

    public function goodsDetail(){
        if(request()->isPost()) {
            $data = $this->request->post();
            $data['details'] = base64_decode($data['details']);
            if ($data['mode'] == 0) {
                $data['type_id'] = 0;
                unset($data['item']);
                $barcodes = explode(",", $data['barcodes']);
                if (count($barcodes) != $data['store']) {
                    return json(array('code' => 0, 'msg' => '库存和条形码数量不一样'));
                }
            } else {
                foreach ($data['item'] as $k => $item) {
                    $barcodes = explode(",", $item['barcodes']);
                    if (count($barcodes) != $item['store']) {
                        return json(array('code' => 0, 'msg' => '库存和条形码数量不一样'));
                    }
                }
            }

            if (count($data['delivery']) == 2) {
                $data['delivery'] = 0;
            } else {
                if (empty($data['delivery'][0])) {
                    $data['delivery'] = 2;
                } else {
                    $data['delivery'] = 1;
                }
            }


            $this->model->startTrans();
            $this->SpecGoodsPrice->startTrans();
            $this->goods_label->startTrans();
            $this->code->startTrans();

            try {
                $data['details'] = str_replace("http://gemshare.oss-cn-shenzhen.aliyuncs.com/goods","/goods",$data['details']);

                if(empty($data['label'])){
                    return json(array('code' => 0, 'msg' => '添加失败，标签为空'));
                }
                //商品标签//查询是否存在,切割成字符串
                $data['label_id'] = implode(",",$data['label']);
                unset($data['label']);
                $goods_label_id = Db::name('goods_label')->where("goods_id={$data['goods_id']}")->field('goods_label_id')->find();
                $data['goods_label_id'] = $goods_label_id['goods_label_id'];
                $result = $this->goods_label->edit($data);
                $result = $this->model->edit($data);
            if ($data['mode'] == 0) {
                $spec_goods_price = Db::name("spec_goods_price")->where("goods_id={$data['goods_id']}")->find();
                if ($spec_goods_price['price_key'] != 0) {
                    $result = $this->SpecGoodsPrice->destroy(['goods_id' => $data['goods_id']]);
                    $price_id = $this->SpecGoodsPrice->add($data);
                    $this->code->destroy(['price_id' => $spec_goods_price['price_id'],'state'=>0]);
                    foreach ($barcodes as $key => $val) {
                        $goodscode[$key]['price_id'] = $price_id;
                        $goodscode[$key]['barcodes'] = $val;
                    }
                    $goodsid = $this->code->saveAll($goodscode);

                } else {
                    if(!$spec_goods_price['price_id']){
                        $priceId = $this->SpecGoodsPrice->add($data);
                        $data['price_id'] = $priceId;
                        $spec_goods_price['price_id'] = $priceId;
                    }else{
                        $data['price_id'] = $spec_goods_price['price_id'];
                        $this->SpecGoodsPrice->edit($data);
                    }

                    $coode_bracode = implode(",",$barcodes);
                    $where['barcodes'] = array('not in',$coode_bracode);
                    $where['price_id'] = $spec_goods_price['price_id'];
                    $codeid = Db::name('code')->where($where)->select();
                    if($codeid){
                        foreach ($codeid as $k => $item) {
                             $this->code->destroy(['code_id'=>$item['code_id'],'state'=>0]);
                        }
                    }
                    foreach ($barcodes as $key => $val) {
                        $codedata['price_id'] = $spec_goods_price['price_id'];
                        $codedata['barcodes'] = $val;
                        $code_i = Db::name('code')->where($codedata)->find();
                        if(!$code_i){
                            $result = $this->code->add($codedata);
                        }
                    }
                }
            } else {
                $id = $data['goods_id'];
                $specStock = Db::name('spec_goods_price')->where('goods_id = '.$data['goods_id'])->column('price_key');
                if(empty($specStock[0])){
                    $this->SpecGoodsPrice->destroy(['goods_id'=>$id]);
                    $price_id = Db::name('spec_goods_price')->field('price_id')->where('goods_id = '.$data['goods_id'])->find();
                    $this->code->destroy(['price_id'=>$price_id['price_id'],'state'=>0]);
                }
                foreach ($specStock as $key=>$time){
                    if(!empty($time)){
                        $specStocks[$time] = $time;
                    }
                }

                if ($data['item']) {
                    $keyArr = '';//规格key数组
                    foreach ($data['item'] as $k => $v) {
                        if($v['settlement_price']==0 || $v['price']==0){
                            $this->error('操作失败,价格不能为0');
                        }

                        $keyArr .= $k.',';
                        // 批量添加数据
                        $v['price'] = trim($v['price']);
                        $v['cost_price'] = trim($v['cost_price']);
                        $v['settlement_price'] = trim($v['settlement_price']);
                        $v['store'] = trim($v['store']);
                        $v['store'] = trim($v['store']);
                        $v['market_price'] = trim($v['market_price']);
                        $data1 = ['goods_id' => $id,'market_price'=>$v['market_price'],'store' => $v['store'], 'price_key' => $k, 'price_key_name' => $v['price_key_name'], 'price' => $v['price'], 'cost_price' => $v['cost_price'],'price' => $v['price'], 'settlement_price' => $v['settlement_price']];


                        if (!empty($specStocks[$k])) {
                            Db::table('je_spec_goods_price') ->where(['goods_id' => $id, 'price_key' => $k])->update($data1);
                        } else {
                            $price_id = $this->SpecGoodsPrice->add($data1);
                        }
                        $price = Db::name('spec_goods_price')->where("goods_id={$id} and price_key={$k}")->find();

                        $coode_bracode1 = implode(",",$v['barcodes']);
                        $where1['barcodes'] = array('not in',$coode_bracode1);
                        $where1['price_id'] = $price['price_id'];

                        $codeid = Db::name('code')->where($where1)->select();
                        if($codeid){
                            foreach ($codeid as $k => $item) {
                                $this->code->destroy(['code_id'=>$item['code_id'],'state'=>0]);
                            }
                        }
                        $barcodes = explode(",",$v['barcodes']);
                        foreach ($barcodes as $key => $val) {
                            $codedata1['price_id'] = $price['price_id'];
                            $codedata1['barcodes'] = $val;
                            $code_i = Db::name('code')->where($codedata1)->find();
                            if(!$code_i){
                                $result = $this->code->add($codedata1);
                            }
                        }

                    }

                    $map['price_key'] =array('not in',$keyArr);
                    $map['goods_id'] = $id;
                    $this->SpecGoodsPrice->destroy($map);

                }else{
                    $map['goods_id'] = $id;
                    $this->SpecGoodsPrice->destroy($map);
                }

            }

                $this->model->commit();
                $this->SpecGoodsPrice->commit();
                $this->goods_label->commit();
                $this->code->commit();
                return json(array('code' => 200, 'msg' => '编辑成功'));

            }catch(\Exception $e){
                $this->model->rollback();
                $this->SpecGoodsPrice->rollback();
                $this->goods_label->rollback();
                $this->code->rollback();
                return json(array('code' => 0, 'msg' => '编辑失败'));
            }
        }



        $label = Db::name('label')->select();
        foreach ($label as $key=>$val){
            if($val['parent_id']==0){
                $label2[$key] = $val;
                unset($label[$key]);
            }
            foreach ($label2 as $k=>$v){
                if($val['parent_id']==$v['label_id']){
                    $label2[$k]['names'][$key] = $val;
                }
            }
        }
        $Materiel = Db::name('materiel')->select();
        foreach ($Materiel as $key=>$val){
            if($val['parent_id']==0){
                $Materiel2[$key] = $val;
                unset($Materiel[$key]);
            }
            foreach ($Materiel2 as $k=>$v){
                if($val['parent_id']==$v['materiel_id']){
                    $Materiel2[$k]['names'][$key] = $val;
                }
            }
        }
        $goods_type = Db::name('goods_type')->select();
        $list = $this->model->where('goods_id',input('param.id'))->find();
        $goods_lable = Db::name('goods_label')->where('goods_id',input('param.id'))->find();
        $goodsLable = explode(",",$goods_lable['label_id']);
        foreach ($goodsLable as $k=>$t){
            $goodsLable2[$k]['label_id'] = $t;
        }
        $list['store_name'] = Db::name('store')->where('store_id',$list['store_id'])->value('name');
        $store = Db::name('store')->select();
        $spec_goods_price = Db::name('spec_goods_price')->where('goods_id',input('param.id'))->find();
        $code = Db::name('code')->where(['price_id'=>$spec_goods_price['price_id'],'state'=>0])->select();
        $code['barcodes'] = array_column($code,barcodes);
        $spec_goods_price['barcodes'] = implode(",",$code['barcodes']);

        $list = $list->toArray();

        $list['details'] = str_replace("/goods","http://gemshare.oss-cn-shenzhen.aliyuncs.com/goods",$list['details']);
        $materiel_id_code = Db::name('materiel')->where("materiel_id={$list['materiel_id']}")->field('parent_id,materiel_id')->find();

        if($materiel_id_code['parent_id']!=0){
            $materiel_id_ = Db::name('materiel')->where("materiel_id={$materiel_id_code['parent_id']}")->field('parent_id,materiel_id')->find();

            $list['materiel_id_s'] = $materiel_id_['materiel_id'];
        }else{
            $list['materiel_id_s'] = $materiel_id_code['materiel_id'];
        }

        return view('goods_detail',['list'=>$list,'store'=>$store,'materiel'=>$Materiel2,'label'=>$label2,'goods_type'=>$goods_type,'goods_lable'=>$goodsLable2,'spec_goods_price'=>$spec_goods_price]);
    }

    //选择商品的某件编码已售  并减少库存
    public function goodsStore(){
        $goods_id = input('get.id');
        $spec_info = db('spec_goods_price')->field('price_key,price_key_name,store')->where("goods_id = {$goods_id}")->select();
        foreach($spec_info as $key=>$value){
            if($value['price_key'] == 0){
                $spec_info[$key]['price_key_name'] = '一口价商品';
            }
            $price_id = db('spec_goods_price')->where("goods_id = {$goods_id} AND price_key = {$value['price_key']}")->value('price_id');
            $code_info = db('code')->field('code_id,price_id,barcodes,state,update_time,sale_type')->where("price_id = {$price_id}")->select();
            $spec_info[$key]['code_info'] = $code_info;
        }
        $this->assign('spec_info',$spec_info);
        return $this->fetch();
    }

    //获取code
    public function getCode(){
        if($this->request->isPost()){
            $goods_id = input('post.goods_id');
            $price_key = input('post.price_key');
            $price_id = db('spec_goods_price')->where("goods_id = {$goods_id} AND price_key = {$price_key}")->value('price_id');
            $code_info = db('code')->field('code_id,price_id,barcodes,state')->where("price_id = {$price_id}")->select();
            if($code_info){
                return json_encode(['code'=>200,'code_info'=>$code_info]);
            }else{
                return json_encode(['code'=>201,'msg'=>'']);
            }
        }
    }

    //选择商品的某件编码已售  并减少库存
    public function changeCodeState(){
        if($this->request->isPost()){
            $store_id = session('store_id');
            $code_id = input('post.code_id');
            $price_id = input('post.price_id');
            $where = "code_id = {$code_id}";
            $code_state = db('code')->where($where)->value('state');
            if($code_state != 0){
                return json(['code'=>401,'msg'=>'编码已出售']);
            }
            $map = "price_id = {$price_id}";
            $goods_store = db('spec_goods_price')->where($map)->value('store');
            if($goods_store <= 0){
                return json(['code'=>401,'msg'=>'该商品已无库存']);
            }
            $data = ['state'=>1,'update_time'=>time(),'admin_user_id'=>'store_id_'.$store_id,'sale_type'=>2];
            Db::startTrans();
            try{
                $change_code_state = db('code')->where($where)->update($data);
                $decrease_stock = db('spec_goods_price')->where($map)->setDec('store');
                Db::commit();
                return json(['code'=>200,'msg'=>'出售成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code'=>201,'msg'=>'出售失败']);
            }
        }
    }
}